Imports System.Data.SqlClient

'--- Created By : Priyabrata
'--- Created On : 28-Sep-2010

Public Class frmSOAP
    Dim mstrMode As String
    Dim mlngRecordID As Long
    Dim blnUnload As Boolean
    Dim mblnChanged As Boolean
    Dim mblnActivate As Boolean
    Dim mblnCancelDisplay As Boolean

    Dim VisitId As Integer

    Public Sub New(ByVal VisitId As Integer)

        ' This call is required by the Windows Form Designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.
        Me.VisitId = VisitId
    End Sub

    Private Sub frmSOAP_Activated(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Activated
        Try
            If mblnActivate = True Then
                mblnActivate = False
                Dim dsTemp As DataSet
                Dim strText As String = ""
                dsTemp = FillDataSet("SELECT  tblPatientInfo.PatientId as PatientId,  tblPatientInfo.FirstName + ' ' + tblPatientInfo.LastName AS Name, CAST(tblVisits.VisitDate AS VARCHAR) AS VisitDate  FROM  tblPatientInfo INNER JOIN  tblVisits ON tblPatientInfo.PatientId = tblVisits.PatientId WHERE  tblVisits.VisitId = " & VisitId)
                If dsTemp.Tables(0).Rows.Count > 0 Then
                    strText = dsTemp.Tables(0).Rows(0).Item("Name") & " " & dsTemp.Tables(0).Rows(0).Item("VisitDate")
                End If
                Me.Text = strText

                PopulateLookupDX(lkAssessment, "Diagnosis", "DiagnosisId", "LtblDiagnosis", "DiagnosisId,Diagnosis", , "Diagnosis", True)
                PopulateLookupDX(lkSeverity, "DiagnosisSeverity", "DiagnosisSeverityId", "LtblDiagnosisSeverity", "DiagnosisSeverityId,DiagnosisSeverity", , "DiagnosisSeverity", True)

                PopulateLookupDX(lkBloodSugar, "BloodSugarUnit", "BloodSugarID", "LtblUnitsBloodSugar", "BloodSugarID,BloodSugarUnit", "", "BloodSugarUnit")
                'lkBloodSugar.ItemIndex = 0
                PopulateLookupDX(lkTemperatureUnit, "TempUnit", "TempUnitId", "LtblUnitsTemp", "TempUnitId,TempUnit", "", "TempUnit")
                'lkTemperatureUnit.ItemIndex = 1
                'PopulateList(lstSpecialists, "SELECT DoctorId,(Firstname + ' ' + Lastname) as Name FROM tblSpecialists ORDER BY Name", "Name", "DoctorId")
                Call PopulateCheckedListboxDX(lstSpecialists, "Name", "DoctorId", "tblSpecialists", "DoctorId,(Firstname + ' ' + Lastname) as Name", , "Name")

                'lkBloodSugar.ItemIndex = 0
                'lkTemperatureUnit.ItemIndex = 0

                'Call UpdateTable("tblVisits", "PatientStatusId= " & PatientStatus.WithDoctor, "VisitId=" & VisitId)
                Call ChangeStatus(VisitId, PatientStatus.WithDoctor)

                Call DisplayData()
                HLinkPC.Focus()
            End If
        Catch ex As Exception
            pbRecords.Visible = False
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub frmSOAP_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        Try
            Dim intUnload As DialogResult

            If mblnChanged = True Then
                intUnload = MessageBox.Show("Is Doctor's visit complete?", gstrMessage, MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1)
                If intUnload = Windows.Forms.DialogResult.No Then
                    Call ChangeStatus(VisitId, PatientStatus.AwaitingDoctor)
                    Exit Sub
                ElseIf intUnload = Windows.Forms.DialogResult.Yes Then
                    blnUnload = True
                    If blnSaveRecords() = False Then
                        e.Cancel = True
                        blnUnload = False
                        Exit Sub
                    End If
                    mblnChanged = False
                End If
            End If
            blnUnload = False
        Catch ex As Exception
            blnUnload = False
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub frmSOAP_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Try
            Call SetImageControl(Me)
            Me.Icon = System.Drawing.Icon.FromHandle(CType(mdiMain.imgFormIcons.Images(2), Bitmap).GetHicon())
            Call GetAccessPermission(Me, "frmSOAP")

            mblnActivate = True
            mblnChanged = True
            ChangeStatus(VisitId, PatientStatus.WithDoctor)
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub DisplayData()
        'Display data in form fields.
        Dim dsTemp As DataSet
        Dim strQuery As String
        Try
            mstrMode = "Add"
            strQuery = "SELECT PresentingComplaint, History, Gen, ENT, RS, CVS, Abd, Mu_SK, NS FROM tblVisits LEFT JOIN tblVisitSummary ON tblVisits.VisitId = tblVisitSummary.VisitId WHERE tblVisits.VisitId=" & VisitId
            dsTemp = FillDataSet(strQuery)

            With dsTemp.Tables(0)
                If .Rows.Count > 0 Then
                    'txtHeight.EditValue = IIf(Val(.Rows(0).Item("Height") & "") = 0, DBNull.Value, Val(.Rows(0).Item("Height") & ""))
                    txtPC.EditValue = .Rows(0).Item("PresentingComplaint")
                    txtHistory.EditValue = .Rows(0).Item("History")
                    txtGen.EditValue = .Rows(0).Item("Gen")
                    txtENT.EditValue = .Rows(0).Item("ENT")
                    txtRS.EditValue = .Rows(0).Item("RS")
                    txtCVS.EditValue = .Rows(0).Item("CVS")
                    txtAbd.EditValue = .Rows(0).Item("Abd")
                    txtMu_SK.EditValue = .Rows(0).Item("Mu_SK")
                    txtNS.EditValue = .Rows(0).Item("NS")

                    mstrMode = "Edit"
                End If
            End With

            strQuery = " SELECT RespiratoryRate, BPSupineS, BPSupineD, " & _
                     " tblVisitCardiology.Pulse AS Pulse, " & _
                     " Temperature, TemperatureUnits, " & _
                     " BloodSugar,BloodSugarUnit, tblVisitResult.Therapy as Therapy" & _
                     " FROM (((((tblVisits LEFT OUTER JOIN tblVisitBPPulse " & _
                     " ON tblVisits.VisitId = tblVisitBPPulse.VisitId )" & _
                     " LEFT OUTER JOIN tblVisitRespiratory " & _
                     " ON tblVisits.VisitID = tblVisitRespiratory.VisitID) " & _
                     " LEFT OUTER JOIN tblVisitGeneralAssessment " & _
                     " ON tblVisits.VisitID=tblVisitGeneralAssessment.VisitID)" & _
                     " LEFT OUTER JOIN tblVisitCardiology " & _
                     " ON tblVisits.VisitID = tblVisitCardiology.VisitID) " & _
                     " LEFT OUTER JOIN tblVisitGenitoUrinary " & _
                     " ON tblVisits.VisitID = tblVisitGenitoUrinary.VisitID)" & _
                     " LEFT OUTER JOIN tblVisitResult " & _
                     " ON tblVisits.VisitID = tblVisitResult.VisitID" & _
                     " WHERE tblVisits.VisitId = " & VisitId

            dsTemp = FillDataSet(strQuery)

            With dsTemp.Tables(0)
                If .Rows.Count > 0 Then
                    'txtBloodSugar.EditValue = IIf(Val(.Rows(0).Item("BloodSugar") & "") = 0, DBNull.Value, Val(.Rows(0).Item("BloodSugar") & ""))
                    txtR.EditValue = IIf(Val(.Rows(0).Item("RespiratoryRate") & "") = 0, DBNull.Value, Convert.ToInt32(Val(.Rows(0).Item("RespiratoryRate") & "")))

                    txtT.EditValue = IIf(Val(.Rows(0).Item("Temperature") & "") = 0, DBNull.Value, Convert.ToInt64(Val(.Rows(0).Item("Temperature") & "")))
                    If IsDBNullOrNothing(.Rows(0).Item("TemperatureUnits")) Then
                        lkTemperatureUnit.ItemIndex = 0
                    Else
                        lkTemperatureUnit.EditValue = Val(.Rows(0).Item("TemperatureUnits"))
                    End If

                    txtP.EditValue = IIf(Val(.Rows(0).Item("Pulse") & "") = 0, DBNull.Value, Convert.ToInt32(Val(.Rows(0).Item("Pulse") & "")))
                    txtBPSupineS.EditValue = IIf(Val(.Rows(0).Item("BPSupineS") & "") = 0, DBNull.Value, Convert.ToInt32(Val(.Rows(0).Item("BPSupineS") & "")))
                    txtBPSupineD.EditValue = IIf(Val(.Rows(0).Item("BPSupineD") & "") = 0, DBNull.Value, Convert.ToInt32(Val(.Rows(0).Item("BPSupineD") & "")))

                    txtBloodSugar.EditValue = IIf(Val(.Rows(0).Item("BloodSugar") & "") = 0, DBNull.Value, Convert.ToDouble(Val(.Rows(0).Item("BloodSugar") & "")))
                    If IsDBNullOrNothing(.Rows(0).Item("BloodSugarUnit")) Then
                        lkBloodSugar.ItemIndex = 0
                    Else
                        lkBloodSugar.EditValue = Val(.Rows(0).Item("BloodSugarUnit"))
                    End If
                    txtTreatment.EditValue = .Rows(0).Item("Therapy") & ""
                    mstrMode = "Edit"
                End If
            End With

            strQuery = "SELECT SpecialistId  as DoctorId FROM tblVisitReferrals WHERE VisitId=" & VisitId
            dsTemp = FillDataSet(strQuery, "VisitReferrals")
            Dim i As Integer
            With dsTemp.Tables(0)
                If .Rows.Count > 0 Then
                    'populate VisitReferrals checked list box
                    For i = 0 To .Rows.Count - 1
                        With lstSpecialists
                            For intCtr As Integer = 0 To .ItemCount
                                If .GetItemValue(intCtr) = dsTemp.Tables("VisitReferrals").Rows(i).Item("DoctorId") Then
                                    .SetItemCheckState(intCtr, CheckState.Checked)
                                End If
                            Next intCtr
                        End With
                    Next
                    

                    mstrMode = "Edit"
                End If
            End With

            strQuery = "SELECT TestType, Test FROM tblVisitInvestigations WHERE VisitID =" & VisitId
            dsTemp = FillDataSet(strQuery, "VisitInvestigation")

            For i = 0 To dsTemp.Tables("VisitInvestigation").Rows.Count - 1
                If dsTemp.Tables("VisitInvestigation").Rows(i).Item("TestType") = "Other Test" Then
                    txtInv.Text = dsTemp.Tables("VisitInvestigation").Rows(i).Item("Test")
                End If
            Next

            dsTemp.Dispose()

        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub btnClose_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnClose.Click
        Me.Close()
    End Sub

    Private Function IsValidEntry() As Boolean
        'Here check valid entry of fields
        Dim strMsg As String = ""
        IsValidEntry = False

        If Not IsDBNullOrNothing(txtR.Text) Then
            If Val(txtR.EditValue) <= 0 Then
                strMsg = "Please enter valid Respiratory Rate."
                txtR.Focus()
                txtR.SelectAll()
            End If
        End If

        'Check for valid temparature
        If Not IsDBNullOrNothing(txtT.Text) Then
            If Val(txtT.EditValue & "") <= 0 Then
                strMsg = "Please enter proper Temperature."
                txtT.Focus()
                txtT.SelectAll()
            End If
        End If
        If Trim(strMsg) <> "" Then
            IsValidEntry = False
            MessageBox.Show(strMsg, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Information)
        Else
            IsValidEntry = True
        End If
    End Function

    Private Function blnSaveRecords() As Boolean
        Dim blnIsTransactionOpen As Boolean

        Try
            blnSaveRecords = False

            If IsValidEntry() = False Then
                Exit Function
            End If

            If (blnUnload = False) Then
                If (MessageBox.Show("Are you sure to " & IIf(mstrMode = "Add", "add", "modify") & " Summary notes?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = System.Windows.Forms.DialogResult.No) Then
                    txtPC.Focus()
                    Exit Function
                End If
            End If

            gtrnWebPlusMed = gconWebPlusMed.BeginTransaction
            blnIsTransactionOpen = True

            'Save PC and History
            Call SavePresentHistory()
            'Save VisitSummary data.
            Call SaveVisitSummary()
            'Save Respiratory rate
            Call SaveRespiratory()
            'Save Temparature
            Call SaveTemparature()
            'Save Pulse
            Call SavePulse()
            'Save BloodSugar
            Call SaveBloodSugar()
            'Save Invectigative (Other Test).
            Call SaveInv()
            'Save Treatment (Therapeutic)
            Call SaveTreatment()
            'Save Refferals
            Call SaveRefferals()
            'Save BP
            Call SaveBP()

            blnSaveRecords = True

            gtrnWebPlusMed.Commit()
            blnIsTransactionOpen = False
            MessageBox.Show("Summary notes saved.", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Information)
        Catch ex As Exception
            If blnIsTransactionOpen = True Then
                gtrnWebPlusMed.Rollback()
            End If
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Function

    Public Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
        Try
            If blnSaveRecords() = False Then Exit Sub
            mblnChanged = False

        Catch ex As Exception
            pbRecords.Visible = False
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub SavePresentHistory()
        Cursor.Current = Cursors.WaitCursor
        'Record for current visitID is already entered at Patient's registration time, So just modify this record.
        Dim strQuery As String

        Try
            strQuery = "PresentingComplaint=" & SmartReplace(txtPC.EditValue) & ", History=" & SmartReplace(txtHistory.EditValue)
            Call UpdateTable("tblVisits", strQuery, "VisitId=" & VisitId)

        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        Finally
            Cursor.Current = Cursors.Default
        End Try
    End Sub

    Private Sub SaveVisitSummary()
        Cursor.Current = Cursors.WaitCursor
        'Patient is already registered ,so there is no need to check wheather visitId exist or not
        Dim strQuery As String, strFeilds As String, strRowCount As String
        Try
            strRowCount = strRecordID("tblVisitSummary", "count (*)", " VisitId=" & VisitId)
            If Val(strRowCount & "") = 0 Then
                strFeilds = " tblVisitSummary(VisitId, Gen, ENT, RS, CVS, Abd, Mu_SK, NS)"
                strQuery = VisitId & "," & _
                            SmartReplace(txtGen.EditValue) & "," & _
                            SmartReplace(txtENT.EditValue) & "," & _
                            SmartReplace(txtRS.EditValue) & "," & _
                            SmartReplace(txtCVS.EditValue) & "," & _
                            SmartReplace(txtAbd.EditValue) & "," & _
                            SmartReplace(txtMu_SK.EditValue) & "," & _
                            SmartReplace(txtNS.EditValue)

                Call InsertintoTable(strFeilds, strQuery)
            Else
                strQuery = "Gen=" & SmartReplace(txtGen.EditValue)
                strQuery = strQuery & ",ENT=" & SmartReplace(txtENT.EditValue)
                strQuery = strQuery & ",RS=" & SmartReplace(txtRS.EditValue)
                strQuery = strQuery & ",CVS=" & SmartReplace(txtCVS.EditValue)
                strQuery = strQuery & ",Abd=" & SmartReplace(txtAbd.EditValue)
                strQuery = strQuery & ",Mu_SK=" & SmartReplace(txtMu_SK.EditValue)
                strQuery = strQuery & ",NS=" & SmartReplace(txtNS.EditValue)

                Call UpdateTable("tblVisitSummary", strQuery, " VisitId=" & VisitId)
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        Finally
            Cursor.Current = Cursors.Default
        End Try
    End Sub

    Private Sub SaveRespiratory()
        Cursor.Current = Cursors.WaitCursor
        'Save Respiratory rate
        Dim strQuery As String, strFeilds As String, strRowCount As String
        Try
            strRowCount = strRecordID("tblVisitRespiratory", "count (*)", " VisitId=" & VisitId)
            If Val(strRowCount & "") = 0 Then
                strFeilds = " tblVisitRespiratory( VisitId,RespiratoryRate)"
                strQuery = VisitId & "," & Val(txtR.EditValue & "")

                Call InsertintoTable(strFeilds, strQuery)
            Else
                strQuery = "RespiratoryRate=" & Val(txtR.EditValue & "")

                Call UpdateTable("tblVisitRespiratory", strQuery, " VisitId=" & VisitId)
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        Finally
            Cursor.Current = Cursors.Default
        End Try
    End Sub

    Private Sub SaveTemparature()
        Cursor.Current = Cursors.WaitCursor
        'Save Respiratory rate
        Dim strQuery As String, strFeilds As String, strRowCount As String
        Try
            strRowCount = strRecordID("tblVisitGeneralAssessment", "count (*)", " VisitId=" & VisitId)
            If Val(strRowCount & "") = 0 Then
                strFeilds = " tblVisitGeneralAssessment(VisitId,Temperature,TemperatureUnits)"

                strQuery = VisitId & "," & Val(txtT.EditValue & "") & "," & IIf(IsDBNullOrNothing(lkTemperatureUnit.EditValue), "NULL", lkTemperatureUnit.EditValue)

                Call InsertintoTable(strFeilds, strQuery)
            Else
                strQuery = "Temperature=" & Val(txtT.EditValue & "") & ",TemperatureUnits=" & IIf(IsDBNullOrNothing(lkTemperatureUnit.EditValue), "NULL", lkTemperatureUnit.EditValue)

                Call UpdateTable("tblVisitGeneralAssessment", strQuery, " VisitId=" & VisitId)
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        Finally
            Cursor.Current = Cursors.Default
        End Try
    End Sub

    Private Sub SavePulse()
        Cursor.Current = Cursors.WaitCursor
        'Save Respiratory rate
        Dim strQuery As String, strFeilds As String, strRowCount As String
        Try
            strRowCount = strRecordID("tblVisitCardiology", "count (*)", " VisitId=" & VisitId)
            If Val(strRowCount & "") = 0 Then
                strFeilds = " tblVisitCardiology(VisitId,Pulse)"

                strQuery = VisitId & "," & Val(txtP.EditValue & "")

                Call InsertintoTable(strFeilds, strQuery)
            Else
                strQuery = "Pulse=" & Val(txtP.EditValue & "")

                Call UpdateTable("tblVisitCardiology", strQuery, " VisitId=" & VisitId)
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        Finally
            Cursor.Current = Cursors.Default
        End Try
    End Sub

    Private Sub SaveBP()
        Cursor.Current = Cursors.WaitCursor
        'Save Respiratory rate
        Dim strQuery As String, strFeilds As String, strRowCount As String
        Try
            strRowCount = strRecordID("tblVisitBPPulse", "count (*)", " VisitId=" & VisitId)
            If Val(strRowCount & "") = 0 Then
                strFeilds = " tblVisitBPPulse(VisitId,BPSupineS,BPSupineD)"

                strQuery = VisitId & "," & Val(txtBPSupineS.EditValue & "") & "," & Val(txtBPSupineD.EditValue & "")

                Call InsertintoTable(strFeilds, strQuery)
            Else
                strQuery = "BPSupineS=" & Val(txtBPSupineS.EditValue & "") & _
                     ",BPSupineD =" & Val(txtBPSupineD.EditValue & "")

                Call UpdateTable("tblVisitBPPulse", strQuery, " VisitId=" & VisitId)
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        Finally
            Cursor.Current = Cursors.Default
        End Try
    End Sub

    Private Sub SaveBloodSugar()
        Cursor.Current = Cursors.WaitCursor
        'Save Blood Sugar
        Dim strQuery As String, strFeilds As String, strRowCount As String
        Try
            strRowCount = strRecordID("tblVisitGenitoUrinary", "count (*)", " VisitId=" & VisitId)
            If Val(strRowCount & "") = 0 Then
                strFeilds = " tblVisitGenitoUrinary(VisitId,BloodSugar,BloodSugarUnit)"

                strQuery = VisitId & "," & Val(txtBloodSugar.EditValue & "") & "," & IIf(IsDBNullOrNothing(lkBloodSugar.EditValue), "NULL", lkBloodSugar.EditValue)

                Call InsertintoTable(strFeilds, strQuery)
            Else
                strQuery = "BloodSugar=" & Val(txtBloodSugar.EditValue & "") & _
                     ",BloodSugarUnit =" & IIf(IsDBNullOrNothing(lkBloodSugar.EditValue), "NULL", lkBloodSugar.EditValue)

                Call UpdateTable("tblVisitGenitoUrinary", strQuery, " VisitId=" & VisitId)
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        Finally
            Cursor.Current = Cursors.Default
        End Try
    End Sub

    Private Sub SaveTreatment()
        Cursor.Current = Cursors.WaitCursor
        'Save Treatment
        Dim strQuery As String, strFeilds As String, strRowCount As String
        Try
            strRowCount = strRecordID("tblVisitResult", "count (*)", " VisitId=" & VisitId)
            If Val(strRowCount & "") = 0 Then
                strFeilds = " tblVisitResult(VisitId,Therapy,Hospitalised)"

                strQuery = VisitId & "," & SmartReplace(txtTreatment.EditValue) & ",0"

                Call InsertintoTable(strFeilds, strQuery)
            Else
                strQuery = "Therapy=" & SmartReplace(txtTreatment.EditValue)

                Call UpdateTable("tblVisitResult", strQuery, " VisitId=" & VisitId)
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        Finally
            Cursor.Current = Cursors.Default
        End Try
    End Sub

    Private Sub SaveInv()
        Cursor.Current = Cursors.WaitCursor
        Dim strQuery As String, strFeilds As String, strRowCount As String
        Try
            strRowCount = strRecordID("tblVisitInvestigations", "count (*)", " VisitId=" & VisitId)
            If Val(strRowCount & "") = 0 Then
                strFeilds = " tblVisitInvestigations(TestType,Test,VisitId)"

                strQuery = "'Other Test'" & ",'" & Replace(txtInv.Text, "'", "''") & "'," & VisitId

                Call InsertintoTable(strFeilds, strQuery)
            Else
                strQuery = "Test='" & Replace(txtInv.Text, "'", "''") & "'"

                Call UpdateTable("tblVisitInvestigations", strQuery, " VisitId=" & VisitId & " AND TestType = 'Other Test'")
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        Finally
            Cursor.Current = Cursors.Default
        End Try
    End Sub

    Private Sub SaveRefferals()
        Cursor.Current = Cursors.WaitCursor
        Dim strQuery As String, strFeilds As String
        Try
            Call DeleteFromTable("tblVisitReferrals", "VisitId=" & VisitId)
            strFeilds = "tblVisitReferrals(SpecialistId,VisitId)"
            With lstSpecialists
                For intCtr As Integer = 0 To .ItemCount
                    If .GetItemCheckState(intCtr) = CheckState.Checked Then
                        strQuery = .GetItemValue(intCtr) & "," & VisitId

                        Call InsertintoTable(strFeilds, strQuery)
                    End If
                Next intCtr
            End With
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        Finally
            Cursor.Current = Cursors.Default
        End Try
    End Sub

    Private Sub txtPS_EditValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtTreatment.EditValueChanged, txtRS.EditValueChanged, txtPC.EditValueChanged, txtNS.EditValueChanged, txtMu_SK.EditValueChanged, txtInv.EditValueChanged, txtHistory.EditValueChanged, txtGen.EditValueChanged, txtENT.EditValueChanged, txtCVS.EditValueChanged, txtAbd.EditValueChanged, lkTemperatureUnit.EditValueChanged, lkSeverity.EditValueChanged, lkBloodSugar.EditValueChanged, lkAssessment.EditValueChanged, txtT.EditValueChanged, txtR.EditValueChanged, txtP.EditValueChanged, txtBPSupineS.EditValueChanged, txtBPSupineD.EditValueChanged, txtBloodSugar.EditValueChanged
        mblnChanged = True
    End Sub

    Private Sub lkAssessment_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles lkAssessment.KeyDown
        Try
            If e.KeyCode = Keys.Enter And lkAssessment.Text <> "" Then

                If IsDBNullOrNothing(lkAssessment.Properties.GetKeyValueByDisplayText(lkAssessment.Text)) = True Then
                    If MessageBox.Show("Diagnosis does not exist." & vbCrLf & "Do you want to add this Diagnosis?", gstrMessage, MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then
                        Dim ModifyDiagnosisForm As New frmToolsLookUp
                        With ModifyDiagnosisForm
                            .mblnFrmOtherForm = True
                            .mstrLookUpValue = "LtblDiagnosis"
                            .mstrItemName = lkAssessment.Text
                            .mintGrbId = 3
                        End With
                        ModifyDiagnosisForm.ShowDialog()
                        If mlngLookUpId > 0 Then
                            PopulateLookupDX(lkAssessment, "Diagnosis", "DiagnosisId", "LtblDiagnosis", "DiagnosisId,Diagnosis", , "Diagnosis", True)
                            lkAssessment.EditValue = CInt(mlngLookUpId)
                        Else
                            lkAssessment.EditValue = Nothing
                            lkAssessment.Focus()
                        End If
                    Else
                        e.Handled = True
                        Exit Sub
                    End If
                End If
            ElseIf e.KeyCode = Keys.Enter And lkAssessment.Text = "" Then
                lkAssessment.ItemIndex = 0
            End If
            mlngLookUpId = Nothing
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub txtR_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtR.KeyPress, txtP.KeyPress, txtBPSupineS.KeyPress, txtBPSupineD.KeyPress
        If IsNumeric(e.KeyChar) = False AndAlso Asc(e.KeyChar) <> Keys.Back Then
            e.Handled = True
        End If
    End Sub

    Private Sub lkAssessment_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles _
    lkAssessment.GotFocus, lkSeverity.GotFocus, lkTemperatureUnit.GotFocus, lkBloodSugar.GotFocus
        sender.ShowPopUp()
    End Sub

    Private Sub lkAssessment_ButtonClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraEditors.Controls.ButtonPressedEventArgs) Handles lkAssessment.ButtonClick
        If e.Button.Index = 1 Then
            PopulateLookupDX(lkAssessment, "Diagnosis", "DiagnosisId", "LtblDiagnosis", "DiagnosisId,Diagnosis", , "Diagnosis", True)
        End If
    End Sub

    Private Sub btnDiagnosisAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDiagnosisAdd.Click
        Try
            If lkAssessment.EditValue = 0 Then
                MessageBox.Show("Please select problem.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                lkAssessment.Focus()
                Exit Sub
            End If
            If lkAssessment.Enabled = False Then Exit Sub

            Dim strFeilds As String = "tblVisitDiagnosis(DiagnosisId,Diagnosis,DiagnosisSeverityId,VisitId,DiagnosisDate,Active,ResolveDate)"
            Dim strQuery As String = lkAssessment.EditValue & ",'" & lkAssessment.Text & "'," & IIf(IsDBNullOrNothing(lkSeverity.EditValue) = True, "NULL", lkSeverity.EditValue) & "," & VisitId & " ,'" & DateTime.Today & "',1,NULL)"
            'Add selected Diagnosis into database and Disable combos.
            Call InsertintoTable(strFeilds, strQuery)

            lkAssessment.Enabled = False
            lkSeverity.Enabled = False
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub txtPC_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtPC.KeyDown, txtTreatment.KeyDown, txtRS.KeyDown, txtNS.KeyDown, txtMu_SK.KeyDown, txtInv.KeyDown, txtHistory.KeyDown, txtGen.KeyDown, txtENT.KeyDown, txtCVS.KeyDown, txtAbd.KeyDown
        If e.KeyCode = Keys.Return Then
            Call NotesFocus(sender)
        End If
    End Sub

    Private Sub HLinkPC_OpenLink(ByVal sender As System.Object, ByVal e As DevExpress.XtraEditors.Controls.OpenLinkEventArgs) Handles HLinkPC.OpenLink

        frmDoctorsNote.VisitId = VisitId
        frmDoctorsNote.DefInstance.MdiParent = Me.ParentForm
        frmDoctorsNote.DefInstance.xtcNotes.SelectedTabPage = frmDoctorsNote.DefInstance.tpgPresentHistory
        frmDoctorsNote.DefInstance.PresentHistory = txtPC.Text
        frmDoctorsNote.DefInstance.Show()
        frmDoctorsNote.DefInstance.BringToFront()
    End Sub

    Private Sub HLinkHistory_OpenLink(ByVal sender As System.Object, ByVal e As DevExpress.XtraEditors.Controls.OpenLinkEventArgs) Handles HLinkHistory.OpenLink
        'link History - takes to Past history tab of Doctor's notes form.

        frmDoctorsNote.VisitId = VisitId
        frmDoctorsNote.DefInstance.MdiParent = Me.ParentForm
        frmDoctorsNote.DefInstance.Show()
        frmDoctorsNote.DefInstance.BringToFront()
        frmDoctorsNote.DefInstance.xtcNotes.SelectedTabPage = frmDoctorsNote.DefInstance.tpgPastHistory
    End Sub

    Private Sub HLinkGen_OpenLink(ByVal sender As System.Object, ByVal e As DevExpress.XtraEditors.Controls.OpenLinkEventArgs) Handles HLinkGen.OpenLink
        'link Gen - takes to General Assessment tab of Doctor's notes form.

        frmDoctorsNote.VisitId = VisitId
        frmDoctorsNote.DefInstance.MdiParent = Me.ParentForm
        frmDoctorsNote.DefInstance.Show()
        frmDoctorsNote.DefInstance.BringToFront()
        frmDoctorsNote.DefInstance.xtcNotes.SelectedTabPage = frmDoctorsNote.DefInstance.tpgGeneralAssessment
    End Sub

    Private Sub HLinkNS_OpenLink(ByVal sender As System.Object, ByVal e As DevExpress.XtraEditors.Controls.OpenLinkEventArgs) Handles HLinkNS.OpenLink
        'link NS - takes to Neurology tab of Doctor's notes form.

        frmDoctorsNote.VisitId = VisitId
        frmDoctorsNote.DefInstance.MdiParent = Me.ParentForm
        frmDoctorsNote.DefInstance.Show()
        frmDoctorsNote.DefInstance.BringToFront()
        frmDoctorsNote.DefInstance.xtcNotes.SelectedTabPage = frmDoctorsNote.DefInstance.tpgNeurology
    End Sub

    Private Sub HLinkEnt_OpenLink(ByVal sender As System.Object, ByVal e As DevExpress.XtraEditors.Controls.OpenLinkEventArgs) Handles HLinkEnt.OpenLink
        'link ENT - takes to Respiratory tab of Doctor's notes form.

        frmDoctorsNote.VisitId = VisitId
        frmDoctorsNote.DefInstance.MdiParent = Me.ParentForm
        frmDoctorsNote.DefInstance.Show()
        frmDoctorsNote.DefInstance.BringToFront()
        frmDoctorsNote.DefInstance.xtcNotes.SelectedTabPage = frmDoctorsNote.DefInstance.tpgRespiratory
    End Sub

    Private Sub HLinkMu_SK_OpenLink(ByVal sender As System.Object, ByVal e As DevExpress.XtraEditors.Controls.OpenLinkEventArgs) Handles HLinkMu_SK.OpenLink
        'link Mu_SK - takes to Locomotion tab of Doctor's notes form.

        frmDoctorsNote.VisitId = VisitId
        frmDoctorsNote.DefInstance.MdiParent = Me.ParentForm
        frmDoctorsNote.DefInstance.Show()
        frmDoctorsNote.DefInstance.BringToFront()
        frmDoctorsNote.DefInstance.xtcNotes.SelectedTabPage = frmDoctorsNote.DefInstance.tpgLocomotion
    End Sub

    Private Sub HLinkRS_OpenLink(ByVal sender As System.Object, ByVal e As DevExpress.XtraEditors.Controls.OpenLinkEventArgs) Handles HLinkRS.OpenLink
        'link RS - takes to Respiratory tab of Doctor's notes form.

        frmDoctorsNote.VisitId = VisitId
        frmDoctorsNote.DefInstance.MdiParent = Me.ParentForm
        frmDoctorsNote.DefInstance.Show()
        frmDoctorsNote.DefInstance.BringToFront()
        frmDoctorsNote.DefInstance.xtcNotes.SelectedTabPage = frmDoctorsNote.DefInstance.tpgRespiratory
    End Sub

    Private Sub HLinkCSV_OpenLink(ByVal sender As System.Object, ByVal e As DevExpress.XtraEditors.Controls.OpenLinkEventArgs) Handles HLinkCSV.OpenLink
        'link CVS - takes to CardioVascular tab of Doctor's notes form.

        frmDoctorsNote.VisitId = VisitId
        frmDoctorsNote.DefInstance.MdiParent = Me.ParentForm
        frmDoctorsNote.DefInstance.Show()
        frmDoctorsNote.DefInstance.BringToFront()
        frmDoctorsNote.DefInstance.xtcNotes.SelectedTabPage = frmDoctorsNote.DefInstance.tpgCardiology
    End Sub

    Private Sub HLinkAbd_OpenLink(ByVal sender As System.Object, ByVal e As DevExpress.XtraEditors.Controls.OpenLinkEventArgs) Handles HLinkAbd.OpenLink
        'link Abd - takes to GastroIntestinal tab of Doctor's notes form.

        frmDoctorsNote.VisitId = VisitId
        frmDoctorsNote.DefInstance.MdiParent = Me.ParentForm
        frmDoctorsNote.DefInstance.Show()
        frmDoctorsNote.DefInstance.BringToFront()
        frmDoctorsNote.DefInstance.xtcNotes.SelectedTabPage = frmDoctorsNote.DefInstance.tpgGastroIntestinal
    End Sub

    Private Sub HLinkUrine_OpenLink(ByVal sender As System.Object, ByVal e As DevExpress.XtraEditors.Controls.OpenLinkEventArgs) Handles HLinkUrine.OpenLink
        'link Urine - takes to GenitoUrinary tab of Doctor's notes form.

        frmDoctorsNote.VisitId = VisitId
        frmDoctorsNote.DefInstance.MdiParent = Me.ParentForm
        frmDoctorsNote.DefInstance.Show()
        frmDoctorsNote.DefInstance.BringToFront()
        frmDoctorsNote.DefInstance.xtcNotes.SelectedTabPage = frmDoctorsNote.DefInstance.tpgGenitoUrinary
    End Sub

    Private Sub HLinkA_OpenLink(ByVal sender As System.Object, ByVal e As DevExpress.XtraEditors.Controls.OpenLinkEventArgs) Handles HLinkA.OpenLink
        'link A - takes to Diagnosis tab of Doctor's notes form.

        frmDoctorsNote.VisitId = VisitId
        frmDoctorsNote.DefInstance.MdiParent = Me.ParentForm
        frmDoctorsNote.DefInstance.Show()
        frmDoctorsNote.DefInstance.BringToFront()
        frmDoctorsNote.DefInstance.xtcNotes.SelectedTabPage = frmDoctorsNote.DefInstance.tpgDiagnosis
    End Sub

    Private Sub HLinkP_OpenLink(ByVal sender As System.Object, ByVal e As DevExpress.XtraEditors.Controls.OpenLinkEventArgs) Handles HLinkP.OpenLink
        'link P - takes to Management tab of Doctor's notes form.

        frmDoctorsNote.VisitId = VisitId
        frmDoctorsNote.DefInstance.MdiParent = Me.ParentForm
        frmDoctorsNote.DefInstance.Show()
        frmDoctorsNote.DefInstance.BringToFront()
        frmDoctorsNote.DefInstance.xtcNotes.SelectedTabPage = frmDoctorsNote.DefInstance.tpgManagement
    End Sub

    Private Sub btnMedical_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnMedical.Click
        ChangeStatus(VisitId, PatientStatus.SeenByDoctor)
    End Sub

    Private Sub btnDetails_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDetails.Click
        frmDoctorsNote.VisitId = VisitId
        frmDoctorsNote.DefInstance.MdiParent = Me.ParentForm
        frmDoctorsNote.DefInstance.Show()
        frmDoctorsNote.DefInstance.BringToFront()
        frmDoctorsNote.DefInstance.xtcNotes.SelectedTabPage = frmDoctorsNote.DefInstance.tpgPresentHistory
    End Sub
End Class
